package com.totcy.interceptor;

import com.totcy.constant.CommonConstant;
import com.totcy.constant.CommonMethod;
import com.totcy.constant.exception.MyIllegalArgumentException;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 异常拦截
 */
public class ExceptionResolveInterceptor implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception exception) {
        PrintWriter writer = null;

        try {
            JSONObject result;

            if(exception instanceof MyIllegalArgumentException){
                result = CommonMethod.responseResult(((MyIllegalArgumentException)exception).getErrorCode(), null);
            }else{
                result = CommonMethod.responseResult(CommonConstant.ErrorCode.CODE5000, new JSONObject());
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            writer = response.getWriter();
            writer.print(result.toString());
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(writer != null){
                writer.close();
            }
        }
        return null;
    }
}
